package com.xxl.sso.server.service.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.xxl.sso.server.core.result.ReturnT;
import com.xxl.sso.server.core.model.User;
import com.xxl.sso.server.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Override
    public ReturnT<User> findUser(String username, String password) {
        if (username==null || username.trim().length()==0) {
            return new ReturnT<User>(ReturnT.FAIL_CODE, "请输入登录账号");
        }
        if (password==null || password.trim().length()==0) {
            return new ReturnT<User>(ReturnT.FAIL_CODE, "请输入密码");
        }
        try {
            List<Entity> list = Db.use("sso").query("select user_id, login_name, user_name, user_type, password, salt, status, del_flag from sys_user where login_name = ?", username);
            if (list == null || list.size() == 0) {
                return new ReturnT<User>(ReturnT.FAIL_CODE, "用户不存在");
            }
            if (list.size() > 1) {
                return new ReturnT<User>(ReturnT.FAIL_CODE, "数据异常");
            }
            Entity entity = list.get(0);
            String delFlag = entity.getStr("del_flag");
            if ("2".equals(delFlag)) {
                return new ReturnT<User>(ReturnT.FAIL_CODE, "用户不存在");
            }
            String status = entity.getStr("status");
            if ("1".equals(status)) {
                return new ReturnT<User>(ReturnT.FAIL_CODE, "用户被禁用");
            }
            //校验密码
            String dbPassword = entity.getStr("password");
            String salt = entity.getStr("salt");
            String loginName = entity.getStr("login_name");
            if (matches(dbPassword, loginName, salt, password)) {
                User u = new User();
                u.setUserId(entity.getLong("user_id"));
                u.setLoginName(loginName);
                u.setUserName(username);
                u.setUserType(entity.getStr("user_type"));
                u.setPassword(dbPassword);
                u.setSalt(salt);
                u.setStatus(status);
                u.setDelFlag(delFlag);
                return new ReturnT<User>(u);
            }
            return new ReturnT<User>(ReturnT.FAIL_CODE, "账号/密码校验失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnT<User>(ReturnT.FAIL_CODE, "服务异常");
        }
    }

    private boolean matches(String dbPassword, String loginName, String salt, String newPassword) {
        return dbPassword.equals(encryptPassword(loginName, newPassword, salt));
    }

    private String encryptPassword(String loginName, String password, String salt) {
        return new Md5Hash(loginName + password + salt).toHex();
    }

}
